import { getAuthHeader } from './auth';
import { BASE_URL } from '@/baseUrl';

interface RequestOptions {
  url: string;
  method: 'GET' | 'POST';
  data?: any;
  header?: Record<string, string>;
  [key: string]: any;
}

export const request = <T>(config: {
  url: string;
  method: string;
  data?: any;
  params?: any;
  header?: any;
}) => {
  return new Promise<T>((resolve, reject) => {
    uni.request({
      url: BASE_URL + config.url,
      method: config.method as any,
      data: config.method === 'GET' ? config.params : config.data,
      header: {
        'Content-Type': 'application/json',
        ...config.header
      },
      success: (res: any) => {
        resolve(res.data as T);
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
};

export const uploadFile = <T>(
  filePath: string,
  options: {
    url: string;
    name?: string;
    formData?: Record<string, any>;
    header?: Record<string, string>;
  }
): Promise<T> => {
  const { url, name = 'file', formData = {}, header = {} } = options;

  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: BASE_URL + url,
      filePath,
      name,
      formData,
      header: {
        ...getAuthHeader(),
        ...header
      },
      success: (res) => {
        try {
          const data = JSON.parse(res.data);
          resolve(data as T);
        } catch (e) {
          reject(new Error('上传响应格式错误'));
        }
      },
      fail: reject
    });
  });
}; 